package com.witmore.neutron.ai.web.wechat.controller;

import com.alibaba.fastjson2.JSONObject;
import com.witmore.neutron.ai.web.filter.AgentLoginRequired;
import com.witmore.neutron.ai.web.filter.GlobalAccountSession;
import com.witmore.neutron.ai.web.wechat.dto.StockAbnormalRecordQueryDTO;
import com.witmore.neutron.ai.web.wechat.dto.StockAlertConfigQueryDTO;
import com.witmore.neutron.ai.web.wechat.service.StockAbnormalRecordService;
import com.witmore.neutron.ai.web.wechat.service.StockAlertConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collections;

/**
 * 微信H5页面控制器
 * Author: 豆子高
 * Date: 2025/12/19
 */
@Slf4j
@Controller
@RequestMapping("/wechat/h5")
@Tag(name = "微信H5页面", description = "微信服务号相关的H5页面")
public class WechatH5Controller extends ScorpionBaseController {

    @Autowired
    private StockAlertConfigService stockAlertConfigService;

    @Autowired
    private StockAbnormalRecordService stockAbnormalRecordService;

    /**
     * 异动配置工具页面
     *
     * @param model    模型
     * @param queryDTO 查询和分页参数
     * @return 页面模板
     */
    @AgentLoginRequired(value = "agentCode")
    @GetMapping("/config-tool/{agentCode}")
    @Operation(summary = "异动配置工具页面", description = "股票异动配置工具的H5页面")
    public String configTool(Model model, @PathVariable("agentCode") String agentCode,
                             StockAlertConfigQueryDTO queryDTO) {
        log.info("访问异动配置工具页面, stockCode: {}, stockName: {}, status: {}, page: {}",
                queryDTO.getStockCode(), queryDTO.getStockName(), queryDTO.getAlertEnabled(), queryDTO.getPage());
        try {
            super.validateUserLogin();

            // 设置默认分页参数
            if (queryDTO.getPage() == null || queryDTO.getPage() <= 0) {
                queryDTO.setPage(1);
            }
            if (queryDTO.getSize() == null || queryDTO.getSize() <= 0) {
                queryDTO.setSize(10);
            }

//            Page<StockAlertConfigDTO> pageResult = stockAlertConfigService.queryAlertConfigs(queryDTO);
//
//            model.addAttribute("title", "异动配置工具");
//            model.addAttribute("description", "股票异动提醒配置工具，帮您监控股票价格异常变动");
//            model.addAttribute("stockCode", queryDTO.getStockCode());
//            model.addAttribute("stockName", queryDTO.getStockName());
//            model.addAttribute("status", queryDTO.getAlertEnabled());
//            model.addAttribute("configList", pageResult.getRecords());
//            model.addAttribute("currentPage", pageResult.getCurrent());
//            model.addAttribute("totalPages", pageResult.getPages());
//            model.addAttribute("totalRecords", pageResult.getTotal());
//            model.addAttribute("isLoggedIn", true);
//            model.addAttribute("openid", GlobalAccountSession.getUserInfo().getScorpionUserOpenid());

//            log.info("获取配置列表数据成功，共{}条记录", pageResult.getTotal());
        } catch (Exception e) {
            log.error("获取配置列表数据失败", e);
            model.addAttribute("title", "异动配置工具");
            model.addAttribute("description", "股票异动提醒配置工具，帮您监控股票价格异常变动");
            model.addAttribute("stockCode", queryDTO.getStockCode());
            model.addAttribute("stockName", queryDTO.getStockName());
            model.addAttribute("status", queryDTO.getAlertEnabled());
            model.addAttribute("configList", Collections.emptyList());
            model.addAttribute("currentPage", queryDTO.getPage());
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("isLoggedIn", true);
            model.addAttribute("errorMessage", "获取数据失败，请稍后重试");
        }

        return "wechat/config-tool";
    }

    /**
     * 配置编辑页面
     *
     * @param model     模型
     * @param agentCode 代理编码
     * @param id        配置ID（可选，新增时为空）
     * @return 页面模板
     */
    @AgentLoginRequired(value = "agentCode")
    @GetMapping("/config-edit/{agentCode}")
    @Operation(summary = "配置编辑页面", description = "股票异动配置的新增/编辑页面")
    public String configEdit(Model model, @PathVariable("agentCode") String agentCode,
                             String id) {
        log.info("访问配置编辑页面, id: {}", id);
        try {
            super.validateUserLogin();

            model.addAttribute("title", id != null ? "编辑配置" : "新增配置");
            model.addAttribute("description", "配置股票异动提醒参数");
            model.addAttribute("configId", id);
            model.addAttribute("isLoggedIn", true);
            model.addAttribute("openid", GlobalAccountSession.getUserInfo().getScorpionUserOpenid());

            log.info("配置编辑页面加载成功");
        } catch (Exception e) {
            log.error("加载配置编辑页面失败", e);
            model.addAttribute("title", "配置编辑");
            model.addAttribute("description", "配置股票异动提醒参数");
            model.addAttribute("configId", id);
            model.addAttribute("isLoggedIn", true);
            model.addAttribute("errorMessage", "页面加载失败，请稍后重试");
        }

        return "wechat/config-edit";
    }

    /**
     * 关于我们页面
     *
     * @param model 模型
     * @return 页面模板
     */
    @GetMapping("/about")
    @Operation(summary = "关于我们页面", description = "关于我们的H5页面")
    public String about(Model model) {
        log.info("访问关于我们页面");
        model.addAttribute("title", "关于我们");
        model.addAttribute("description", "威特猫AI - 专业的人工智能金融服务平台");
        return "wechat/about";
    }

    /**
     * 异动记录页面
     *
     * @param model    模型
     * @param queryDTO 查询和分页参数
     * @return 页面模板
     */
    @AgentLoginRequired(value = "agentCode")
    @GetMapping("/abnormal-record/{agentCode}")
    @Operation(summary = "异动记录页面", description = "股票异动记录查看的H5页面")
    public String abnormalRecord(Model model, @PathVariable("agentCode") String agentCode,
                                 StockAbnormalRecordQueryDTO queryDTO) throws Exception {
        log.info("访问异动记录页面, stockCode: {}, stockName: {}, abnormalType: {}, startDate: {}, endDate: {}, page: {}",
                queryDTO.getStockCode(), queryDTO.getStockName(), queryDTO.getAbnormalTypeCode(), queryDTO.getStartDate(), queryDTO.getEndDate(), queryDTO.getPage());

        super.validateUserLogin();
        try {
            // 设置默认分页参数
            if (queryDTO.getPage() == null || queryDTO.getPage() <= 0) {
                queryDTO.setPage(1);
            }
            if (queryDTO.getSize() == null || queryDTO.getSize() <= 0) {
                queryDTO.setSize(10);
            }
//
//            Page<StockAbnormalRecordDTO> pageResult = stockAbnormalRecordService.queryAbnormalRecords(queryDTO);
//
//            model.addAttribute("title", "异动记录");
//            model.addAttribute("description", "查看股票异动记录，掌握市场动态");
//            model.addAttribute("stockCode", queryDTO.getStockCode());
//            model.addAttribute("stockName", queryDTO.getStockName());
//            model.addAttribute("abnormalType", queryDTO.getAbnormalType());
//            model.addAttribute("startDate", queryDTO.getStartDate());
//            model.addAttribute("endDate", queryDTO.getEndDate());
//            model.addAttribute("recordList", pageResult.getRecords());
//            model.addAttribute("currentPage", pageResult.getCurrent());
//            model.addAttribute("totalPages", pageResult.getPages());
//            model.addAttribute("totalRecords", pageResult.getTotal());
//            model.addAttribute("isLoggedIn", true);
//
//            log.info("获取异动记录数据成功，共{}条记录", pageResult.getTotal());
        } catch (Exception e) {
            log.error("获取异动记录数据失败", e);
            model.addAttribute("title", "异动记录");
            model.addAttribute("description", "查看股票异动记录，掌握市场动态");
            model.addAttribute("stockCode", queryDTO.getStockCode());
            model.addAttribute("stockName", queryDTO.getStockName());
            model.addAttribute("abnormalType", queryDTO.getAbnormalTypeCode());
            model.addAttribute("startDate", queryDTO.getStartDate());
            model.addAttribute("endDate", queryDTO.getEndDate());
            model.addAttribute("recordList", Collections.emptyList());
            model.addAttribute("currentPage", queryDTO.getPage());
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("isLoggedIn", true);
            model.addAttribute("errorMessage", "获取数据失败，请稍后重试");
        }

        return "wechat/abnormal-record";
    }

    /**
     * 股票异动预警详情页面
     */
    @GetMapping("/stock-alert-detail/{alertId}")
    @Operation(summary = "股票异动预警详情页面", description = "微信服务号模板消息跳转的股票异动预警详情H5页面")
    public String stockAlertDetail(Model model, @PathVariable("alertId") Integer alertId) {
        log.info("访问股票异动预警详情页面, alertId: {}", alertId);

        // 获取股票预警详细信息
        Object alertDetail = stockAbnormalRecordService.getAlertDetail(alertId);
        model.addAttribute("alertDetail", JSONObject.from(alertDetail));
        return "wechat/stock-alert-detail";
    }
}
